/**
 * Created on 29 avr. 08 by Sebastian Audet
 */
package maps.editor;

import grid.Grid;
import grid.GridOutOfBounds;
import grid.GridType;
import grid.GridTypeException;
import grid.HexGrid;
import gui2Dengine.HexGridPanel;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigInteger;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.JFrame;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.thereconstruction.map.Layerstype;
import org.thereconstruction.map.Layertype;
import org.thereconstruction.map.Map;
import org.thereconstruction.map.ObjectFactory;
import org.xml.sax.Attributes;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import tile.TileSet;
import tile.XMLTileSet;

/**
 * The purpose of this class is encapsulate methods for interacting with map
 * files. An instance of this class will manage one main map and any child maps,
 * and supports method to interact with the layer files themselves, such as
 * 
 * A map is a collection of map-layers, and a GridType with which to render.
 * Maps are saved in an xml structured file with an extension .map
 * 
 * @author Sebastian Audet
 */
public class MapIO {

    /**
     * Uses an ArrayList to mimic a Set
     * 
     * @author Sebastian Audet
     */
    public class ArrayListSet<T> implements Set<T> {

        ArrayList<T> list = new ArrayList<T>();

        /* (non-Javadoc)
         * @see java.util.Set#add(java.lang.Object)
         */
        public boolean add(T o) {
            if (!contains(o)) {
                list.add(o);
                return true;
            }
            return false;
        }

        /* (non-Javadoc)
         * @see java.util.Set#addAll(java.util.Collection)
         */
        public boolean addAll(Collection<? extends T> c) {
            return list.addAll(c);
        }

        /* (non-Javadoc)
         * @see java.util.Set#clear()
         */
        public void clear() {
            list.clear();
        }

        /* (non-Javadoc)
         * @see java.util.Set#contains(java.lang.Object)
         */
        public boolean contains(Object o) {
            return list.contains(o);
        }

        /* (non-Javadoc)
         * @see java.util.Set#containsAll(java.util.Collection)
         */
        public boolean containsAll(Collection<?> c) {
            return list.containsAll(c);
        }

        /* (non-Javadoc)
         * @see java.util.Set#isEmpty()
         */
        public boolean isEmpty() {
            return list.isEmpty();
        }

        /* (non-Javadoc)
         * @see java.util.Set#remove(java.lang.Object)
         */
        public boolean remove(Object o) {
            return list.remove(o);
        }

        /* (non-Javadoc)
         * @see java.util.Set#removeAll(java.util.Collection)
         */
        public boolean removeAll(Collection<?> c) {
            return list.removeAll(c);
        }

        /* (non-Javadoc)
         * @see java.util.Set#retainAll(java.util.Collection)
         */
        public boolean retainAll(Collection<?> c) {
            return list.retainAll(c);
        }

        /* (non-Javadoc)
         * @see java.util.Set#size()
         */
        public int size() {
            return list.size();
        }

        /* (non-Javadoc)
         * @see java.util.Set#toArray()
         */
        public Object[] toArray() {
            return list.toArray();
        }

        /* (non-Javadoc)
         * @see java.util.Set#toArray(T[])
         */
        @SuppressWarnings("hiding")
        public <T> T[] toArray(T[] a) {
            return list.toArray(a);
        }

        public Iterator<T> iterator() {
            return list.iterator();
        }
    }

    /**
     * Private class to allow easier bookkeeping of the layer-class pairs
     * 
     * @author Sebastian Audet
     */
    private static class URIPair implements Comparable<URIPair> {

        public URI layeruri;
        public URI classuri;

        public URIPair(URI layeruri, URI classuri) {
            this.layeruri = layeruri;
            this.classuri = classuri;
        }

        public int compareTo(URIPair o) {
            if (o.classuri.toString().equals(this.classuri.toString())) {
                if (o.layeruri.toString().equals(this.layeruri.toString())) {
                    return 0;
                } else {
                    return o.layeruri.compareTo(this.layeruri);
                }
            } else {
                return o.classuri.compareTo(this.classuri);
            }
        }

        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Object#equals(java.lang.Object)
         */
        @Override
        public boolean equals(Object obj) {
            if (obj instanceof URIPair) {
                URIPair o = (URIPair) obj;
                if (o.classuri.toString().equals(this.classuri.toString()) && o.layeruri.toString().equals(
                        this.layeruri.toString())) {
                    return true;
                }
            }
            return false;
        }
    }

    // This class may come in handy later perhaps?
    @SuppressWarnings("unused")
    private static class MapContentHandler implements
            org.xml.sax.ContentHandler {

        byte typeswitch = 0;
        byte layerswitch = 0;
        URI temp = null;
        protected int xsize = 0;
        protected int ysize = 0;
        protected GridType gridtype = null;
        protected TreeSet<URIPair> layeruris = new TreeSet<URIPair>();
        protected ArrayList<URI> mapuris = new ArrayList<URI>();
        private boolean throwgridexception = false;

        /*
         * (non-Javadoc)
         * 
         * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String,
         *      java.lang.String, java.lang.String, org.xml.sax.Attributes)
         */
        public void startElement(String uri, String localName, String name,
                Attributes attributes) throws SAXException {
            if (typeswitch == 4) {
                if (localName.equals("maplayer")) {
                    layerswitch = 1;
                } else if (localName.equals("mapclass")) {
                    layerswitch = 2;
                } else if (localName.equals("mapref")) {
                    layerswitch = 3;
                }
            }
            if (localName.equals("xsize")) {
                typeswitch = 1;
            } else if (localName.equals("ysize")) {
                typeswitch = 2;
            } else if (localName.equals("gridtype")) {
                typeswitch = 3;
            } else if (localName.equals("layer")) {
                typeswitch = 4;
            }
        }

        public void characters(char[] ch, int start, int length)
                throws SAXException {
            if (typeswitch != 0) {
                char[] cs = new char[length];
                int incr = 0;
                for (int i = start; i < start + length; i++) {
                    cs[incr] = ch[i];
                    incr++;
                }
                String t = String.copyValueOf(cs);
                switch (typeswitch) {
                    case 1: {
                        xsize = Integer.valueOf(t);
                        break;
                    }
                    case 2: {
                        ysize = Integer.valueOf(t);
                        break;
                    }
                    case 3: {
                        for (GridType gt : GridType.values()) {
                            if (t.equals(gt.getName())) {
                                gridtype = gt;
                            }
                        }
                        if (gridtype == null) {
                            throwgridexception = true;
                        }
                        break;
                    }
                    case 4: {
                        if (layerswitch != 0) {
                            try {
                                switch (layerswitch) {
                                    case 1: {
                                        temp = new URI(t);

                                        break;
                                    }
                                    case 2: {
                                        layeruris.add(new URIPair(temp, new URI(t)));
                                        break;
                                    }
                                    case 3: {
                                        mapuris.add(new URI(t));
                                        break;
                                    }
                                }
                            } catch (URISyntaxException e) {
                                e.printStackTrace();
                            }
                        }
                        break;
                    }
                }
            }
        }

        public void endDocument() throws SAXException {
            // TODO Auto-generated method stub
        }

        public void endElement(String uri, String localName, String name)
                throws SAXException {
            if (typeswitch == 4) {
                if (localName.equals("maplayer")) {
                    layerswitch = 0;
                } else if (localName.equals("mapclass")) {
                    layerswitch = 0;
                } else if (localName.equals("mapref")) {
                    layerswitch = 0;
                }
            }
            if (localName.equals("xsize")) {
                typeswitch = 0;
            } else if (localName.equals("ysize")) {
                typeswitch = 0;
            } else if (localName.equals("layer")) {
                typeswitch = 0;
            } else if (localName.equals("gridtype")) {
                typeswitch = 0;
            }
        }

        public void endPrefixMapping(String prefix) throws SAXException {
            // TODO Auto-generated method stub
        }

        public void ignorableWhitespace(char[] ch, int start, int length)
                throws SAXException {
            // TODO Auto-generated method stub
        }

        public void processingInstruction(String target, String data)
                throws SAXException {
            // TODO Auto-generated method stub
        }

        public void setDocumentLocator(Locator locator) {
            // TODO Auto-generated method stub
        }

        public void skippedEntity(String name) throws SAXException {
            // TODO Auto-generated method stub
        }

        public void startDocument() throws SAXException {
            // TODO Auto-generated method stub
        }

        public void startPrefixMapping(String prefix, String uri)
                throws SAXException {
        }
    }    // The class initially has a default type of hexgrid, a 100x100 grid and no
    // layers or references
    private static final GridType default_grid_type = GridType.HEXGRID;
    private static final int default_xsize = 100;
    private static final int default_ysize = 100;    // Used to hold a backup of the values the document was opened with
    // initially
    private GridType orig_grid_type;
    private int orig_xsize;
    private int orig_ysize;
    private Set<URI> orig_maprefs;
    private Set<URIPair> orig_layers;
    private URI orig_activation;    // Working values
    public GridType curr_grid_type = default_grid_type;
    public int xsize = default_xsize;
    public int ysize = default_ysize;
    private Set<URI> maprefs = new ArrayListSet<URI>();
    private Set<URIPair> layers = new ArrayListSet<URIPair>();
    public URI activation;
    private File xmldoc;
    private Map xmlmap;
    private Layerstype lstype;
    private List<Layertype> xlayers;
    private ObjectFactory factory = new ObjectFactory();
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;
    private JAXBContext context;
    private URI baseURI;

    // Open, Create
    // with
    // URL/File/String
    // and
    // size constraints, URI sets, GridType
    public MapIO(String map) throws FileNotFoundException, GridTypeException,
            URISyntaxException {
        this(new File(map));
    }

    public MapIO(URI map) throws FileNotFoundException, GridTypeException,
            URISyntaxException {
        this(new File(map));
    }

    public MapIO(File map) throws FileNotFoundException, GridTypeException,
            URISyntaxException {
        init(map);
    }

    public MapIO(String map, int xsize, int ysize) throws GridTypeException,
            URISyntaxException {
        this(new File(map), xsize, ysize);
    }

    public MapIO(String map, GridType grid_type) throws GridTypeException,
            URISyntaxException {
        this(new File(map), grid_type);
    }

    public MapIO(String map, int grid_type) throws GridTypeException,
            URISyntaxException {
        this(new File(map), grid_type);
    }

    public MapIO(URI map, int xsize, int ysize) throws GridTypeException,
            URISyntaxException {
        this(new File(map), xsize, ysize);
    }

    public MapIO(URI map, GridType grid_type) throws GridTypeException,
            URISyntaxException {
        this(new File(map), grid_type);
    }

    public MapIO(URI map, int grid_type) throws GridTypeException,
            URISyntaxException {
        this(new File(map), grid_type);
    }

    public MapIO(File map, int xsize, int ysize) throws GridTypeException,
            URISyntaxException {
        init(map);
        this.xsize = xsize;
        this.ysize = ysize;
        mapout();
    }

    public MapIO(File map, GridType grid_type) throws GridTypeException,
            URISyntaxException {
        init(map);
        changeGridType(grid_type);
        mapout();
    }

    public MapIO(File map, int grid_type) throws GridTypeException,
            URISyntaxException {
        init(map);
        changeGridType(grid_type);
        mapout();
    }

    public MapIO(String map, int xsize, int ysize, GridType grid_type)
            throws GridTypeException, URISyntaxException {
        this(new File(map), xsize, ysize, grid_type);
    }

    public MapIO(URI map, int xsize, int ysize, GridType grid_type)
            throws GridTypeException, URISyntaxException {
        this(new File(map), xsize, ysize, grid_type);
    }

    public MapIO(File map, int xsize, int ysize, GridType grid_type)
            throws GridTypeException, URISyntaxException {
        init(map);
        this.xsize = xsize;
        this.ysize = ysize;
        this.curr_grid_type = grid_type;
        mapout();
    }

    /**
     * Intended to do the following:<br>
     * <ol>
     * <li>Resolve an absolute baseURI</li>
     * <li>Set up the required JAXB</li>
     * <li>Set up the map</li>
     * <li>Store the map</li>
     * <li>Set up the URIs</li>
     * <li>Make backups</li>
     * </ol>
     * 
     * @param map
     * @throws GridTypeException
     * @throws URISyntaxException
     */
    private void init(File map) throws GridTypeException, URISyntaxException {
        try {
            baseURI = this.getClass().getResource("../../").toURI();
            xmlinit();
            mapsetup(map);

        } catch (JAXBException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Store the xml File in memory for later use/swapping-out
        xmldoc = map;

        loaduris();

        // Make backups
        databackup();
    }

    /**
     * Take care of the IO needs
     * 
     * @throws JAXBException
     */
    private void xmlinit() throws JAXBException {
        context = JAXBContext.newInstance("org.thereconstruction.map");
        unmarshaller = context.createUnmarshaller();
        marshaller = context.createMarshaller();
    }

    /**
     * Take care of file business //TODO Validation, currently assuming all
     * documents are well-formed and valid.
     * 
     * @param map
     * @throws JAXBException
     * @throws GridTypeException
     * @throws IOException
     */
    public void mapsetup(File map) throws JAXBException, GridTypeException,
            IOException {
        if (map.exists()) {
            xmlmap = (Map) unmarshaller.unmarshal(new FileInputStream(map));
            changeGridType(xmlmap.getGridtype());
            xsize = xmlmap.getXsize().intValue(); // TODO Do away with int
            // restrictions
            ysize = xmlmap.getYsize().intValue(); // TODO Do away with int
            // restrictions
            lstype = xmlmap.getLayers();
            xlayers = lstype.getLayer();
        } else {
            map.createNewFile();
            xmlmap = factory.createMap();
            xmlmap.setGridtype(curr_grid_type.getName());
            xmlmap.setXsize(new BigInteger(String.valueOf(xsize)));
            xmlmap.setYsize(new BigInteger(String.valueOf(ysize)));
            lstype = factory.createLayerstype();
            xmlmap.setLayers(lstype);
            xlayers = lstype.getLayer();
            marshaller.marshal(xmlmap, new FileOutputStream(map));
        }
    }

    private void xmlin() {
        try {
            xmlmap = (Map) unmarshaller.unmarshal(xmldoc);
        } catch (JAXBException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void xmlout() {
        try {
            marshaller.marshal(xmlmap, new FileOutputStream(xmldoc));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (JAXBException e) {
            e.printStackTrace();
        }
    }

    public void mapout() {
        writeGridType();
        writeDimension();
        writeLayers();
        xmlout();
    }

    public void mapin() {
        xmlin();
        readGridType();
        readDimension();
        try {
            loaduris();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    /**
     * 
     */
    public void readDimension() {
        xsize = xmlmap.getXsize().intValue();
        ysize = xmlmap.getYsize().intValue();
    }

    /**
     * 
     */
    public void readGridType() {
        try {
            changeGridType(xmlmap.getGridtype());
        } catch (GridTypeException e) {
            e.printStackTrace();
        }
    }

    /**
     * Load in URIs
     * 
     * @throws URISyntaxException
     */
    /**
     * @throws URISyntaxException
     */
    private void loaduris() throws URISyntaxException {
        layers.clear();
        maprefs.clear();
        for (Layertype layer : xlayers) {
            if (layer.getMapref() == null) { // Is NOT a map reference
                layers.add(new URIPair(new URI(layer.getMaplayer()), new URI(
                        layer.getMapclass())));
            } else {
                maprefs.add(new URI(layer.getMapref()));
            }
        }
        String sact = xmlmap.getActivation();
        if (sact != null) {
            activation = new URI(sact);
        }
    }

    /**
     * 
     */
    private void writeLayers() {
        xlayers.clear();
        for (URIPair layer : layers) {
            Layertype nlayer = factory.createLayertype();
            nlayer.setMaplayer(layer.layeruri.toString());
            nlayer.setMapclass(layer.classuri.toString());
            xlayers.add(nlayer);
        }
        for (URI mapref : maprefs) {
            Layertype nlayer = factory.createLayertype();
            nlayer.setMapref(mapref.toString());
            xlayers.add(nlayer);
        }
        if (activation != null) {
            xmlmap.setActivation(activation.getPath());
        }
    }

    /**
     * 
     */
    private void writeDimension() {
        xmlmap.setXsize(new BigInteger(String.valueOf(xsize)));
        xmlmap.setYsize(new BigInteger(String.valueOf(ysize)));
    }

    /**
     * 
     */
    private void writeGridType() {
        xmlmap.setGridtype(curr_grid_type.getName());
    }

    /**
     * Restore the original data, but does not write to file
     */
    public void restoreorig() {
        curr_grid_type = orig_grid_type;
        xsize = orig_xsize;
        ysize = orig_ysize;
        maprefs = orig_maprefs;
        layers = orig_layers;
        activation = orig_activation;
    }

    /**
     * Backup data
     */
    public void databackup() {
        orig_grid_type = curr_grid_type;
        orig_xsize = xsize;
        orig_ysize = ysize;
        orig_maprefs = maprefs;
        orig_layers = layers;
        orig_activation = activation;
    }

    public void changeGridType(String t) throws GridTypeException {
        for (GridType gt : GridType.values()) {
            if (t.equals(gt.getName())) {
                curr_grid_type = gt;
                return;
            }
        }
        throw new GridTypeException("No such grid type: " + t);
    }

    public void changeGridType(int grid_type) throws GridTypeException {
        for (GridType gt : GridType.values()) {
            if (gt.getType() == grid_type) {
                changeGridType(gt);
                return;
            }
        }
        throw new GridTypeException("No such grid type: " + grid_type);
    }

    public void changeGridType(GridType gt) {
        curr_grid_type = gt;
    }

    public GridType returnGridType() {
        return curr_grid_type;
    }

    public void writeMapLayerOut(File layer, String[][] data) {

        File f = layer;
        try {
            f.delete();
            f.createNewFile();
            BufferedWriter writer = new BufferedWriter(new FileWriter(f));
            for (int i = 0; i < data.length; i++) {
                for (String s : data[i]) {
                    writer.write(s + ",");
                }
                if (i != data.length - 1) {
                    writer.write("\n"); // New line
                }
            }
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public void writeMapLayerOut(URI layer, String[][] data) {
        writeMapLayerOut(new File(layer), data);
    }

    public String[][] readInMapLayer(File layer) {
        File f = layer;
        if (f.exists() && f.isFile()) {
            int x = 0;
            int y = 0;
            ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
            try {
                Scanner reader = new Scanner(new BufferedReader(new FileReader(
                        f)));
                reader.useDelimiter("\n");
                ArrayList<String> lines = new ArrayList<String>();
                while (reader.hasNext()) {
                    lines.add(reader.nextLine());
                }
                reader.close();
                String delim = " ";
                if (lines.get(0).contains(";")) {
                    delim = ";";
                } else if (lines.get(0).contains(",")) {
                    delim = ",";
                }
                for (int i = 0; i < lines.size(); i++) {
                    reader = new Scanner(new BufferedReader(new StringReader(
                            lines.get(i))));
                    reader.useDelimiter(delim);
                    ArrayList<String> temp = new ArrayList<String>();
                    while (reader.hasNext()) {
                        temp.add(reader.next());
                    }
                    data.add(temp);
                }
                for (int l = 0; l < data.size(); l++) {
                    for (int m = 0; m < data.get(l).size(); m++) {
                        String t = data.get(l).get(m);
                        if (!t.equals("0")) {
                            data.get(y).add(t);
                        }
                        if (m > x) {
                            x = m;
                        }
                    }
                    if (l > y) {
                        y = l;
                    }
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            String[][] rdata = new String[y][x];
            for (int i = 0; i < y; i++) {
                for (int j = 0; j < x; j++) {
                    rdata[i][j] = data.get(i).get(j);
                }
            }
            return rdata;
        } else {
            return null;
        }
    }

    public String[][] readInMapLayer(URI layer) {
        return readInMapLayer(new File(layer));
    }

    public URI resolveURI(URI uri) {
        return baseURI.resolve(uri);
    }

    public static void main(String[] args) {
        try {
            MapIO mio = new MapIO("maps/editor/newmap.xml");
            //mio.removemapref(new URI("maps/editor/newmap.xml"));
            HexGrid grid = new HexGrid(30, 60);
            Iterator<URIPair> itr = mio.getLayers().iterator();
            while (itr.hasNext()) {
                URIPair temp = itr.next();
                try {
                    grid.readInGrid(new File(temp.layeruri.getPath()), (TileSet) Class.forName(temp.classuri.getPath()).newInstance());
                } catch (InstantiationException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (GridOutOfBounds e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            //grid.readInActivation(mio.activation.getPath());
            JFrame frame = new JFrame();
            frame.setSize(500, 500);
            HexGridPanel hpan = new HexGridPanel(grid, 1, 500, 500, 30, 60, 0, 0);
            frame.add(hpan);
            frame.setVisible(true);
        } catch (GridTypeException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * Returns all layers recursively, including those in linked maps
     * @return All the layers in this map and in the submaps
     */
    public Set<URIPair> getLayers() { //FIXME Fix loop possibility
        Set<URIPair> c = new ArrayListSet<URIPair>();
        for (URI map : maprefs) {
            try {
                c.addAll(new MapIO(resolveURI(map)).getLayers());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (GridTypeException e) {
                e.printStackTrace();
            } catch (URISyntaxException e) {
                e.printStackTrace();
            }
        }
        layers.addAll(c);
        return layers;
    }

    public void activate(URI uri) {
        activation = uri;
        mapout();
    }

    public void add(URIPair pair) {
        this.layers.add(pair);
        mapout();
    }

    public void addAll(Set<URIPair> pairs) {
        layers.addAll(pairs);
        mapout();
    }

    public void addmapref(URI uri) {
        this.maprefs.add(uri);
        mapout();
    }

    public void addAllmaprefs(Set<URIPair> maprefs) {
        layers.addAll(maprefs);
        mapout();
    }

    public void remove(URIPair pair) {
        this.layers.remove(pair);
        mapout();
    }

    public void removeAll(Set<URIPair> pairs) {
        this.layers.removeAll(pairs);
        mapout();
    }

    public void removemapref(URI uri) {
        this.maprefs.remove(uri);
        mapout();
    }

    public void removeAllmaprefs(Set<URIPair> maprefs) {
        this.layers.removeAll(maprefs);
        mapout();
    }

    @SuppressWarnings("unused")
    private static void pl(TreeSet<URIPair> pairs) {
        for (URIPair urip : pairs) {
            pl("[" + urip.layeruri.toString() + "," + urip.classuri.toString() + "]");
        }
    }

    private static void pl(Object o) {
        System.out.println(o);
    }

    @SuppressWarnings("unused")
    private static void pl(Object[][] o) {
        for (int i = 0; i < o.length; i++) {
            for (int j = 0; j < o.length; j++) {
                pl(o[i][j]);
            }
        }
    }

    public void initializeGrid(Grid grid) {
        Iterator<URIPair> itr = this.getLayers().iterator();
        while (itr.hasNext()) {
            URIPair temp = itr.next();
            try {
                grid.readInGrid(new File(temp.layeruri.getPath()), new XMLTileSet(temp.classuri.getPath()));
            } catch (GridOutOfBounds e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
